package com.example.tse.rbyair.dialog;

import android.app.Dialog;
import android.app.NotificationManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.NotificationCompat;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.example.tse.rbyair.R;

import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.DownloadController;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.log.L;
import org.kymjs.kjframe.utils.FileUtils;

import java.io.File;

public class DownProgressDialog extends DialogFragment {


    private TextView msg;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final Dialog dialog = new Dialog(getActivity(), android.R.style.Theme_Translucent_NoTitleBar);

        Window window = dialog.getWindow();
        WindowManager.LayoutParams wlp = window.getAttributes();
//        window.setWindowAnimations(R.style.dialogWindowAnim); //设置窗口弹出动画
        wlp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wlp.height = WindowManager.LayoutParams.WRAP_CONTENT;//DensityUtils
        wlp.dimAmount = 0.3f;// Range is from 1.0 for completely opaque to 0.0 for no* dim
        wlp.gravity = Gravity.CENTER;

        window.setAttributes(wlp);
//        dialog.setCanceledOnTouchOutside(true);


        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {

                return true;


            }
        });

        return dialog;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.dialog_tips_update, container);

        msg = (TextView) view.findViewById(R.id.msg);
        Button cancel = (Button) view.findViewById(R.id.ok_sure);
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


            }
        });


        downTest();


        return view;
    }


    @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    private NotificationManager mNotificationManager;
    private static final int NOTIFY_ID = 0;
    private static int downLoadProgress = 0;
    private NotificationCompat.Builder builder;

    private void downTest() {

        final KJHttp kjh = new KJHttp();
        final String fileUrl = FileUtils.getSDCardPath() + "/tse.apk";


        kjh.download(
                fileUrl,
                "http://music.baidu.com/cms/mobile/static/apk/Baidumusic_yinyuehexzfc.apk",
                new HttpCallBack() {

                    @Override
                    public void onPreStart() {
                        super.onPreStart();
                        mNotificationManager = (NotificationManager) getActivity().getSystemService(android.content.Context.NOTIFICATION_SERVICE);
                        builder = new NotificationCompat.Builder(getActivity())
                                .setSmallIcon(R.drawable.ic_launcher)
                                .setContentTitle("Picture Download")
                                .setContentText("Download in progress");
                        builder.setAutoCancel(true);

                    }

                    @Override
                    public void onLoading(long count, long current) {
                        super.onLoading(count, current);
                        DownloadController downn = kjh.getDownloadController(fileUrl,
                                "http://music.baidu.com/cms/mobile/static/apk/Baidumusic_yinyuehexzfc.apk");

//                        L.d("WelcomeActivity  downn getStatus():" + downn.getStatus() + " downn:" + downn.isDownloading());

//                        L.d(count + "====" + current);

                        int totla = 100;
                        final int now = (int) ((int) current * 100 / count);


                        L.d(totla + "====" + now);

                        if (now > downLoadProgress) {

                            downLoadProgress = now;
                            L.d(now + "====" + downLoadProgress);

                            builder.setContentTitle("" + 100).setContentText("" + now).setProgress(totla, now, false);

                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    msg.setText(now + "%");

                                }
                            });
                            mNotificationManager.notify(NOTIFY_ID, builder.build());
                        }


                    }

                    @Override
                    public void onSuccess(byte[] t) {
                        super.onSuccess(t);

                        L.d("完成 t:" + t);

                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        File apkFile = new File(fileUrl);
                        intent.setDataAndType(Uri.fromFile(apkFile),
                                "application/vnd.android.package-archive");
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                        getActivity().startActivity(intent);

                        long fileLengh = apkFile.length();
                        L.d("WelcomeActivity fileLengh:" + fileLengh);

//                        L.d("WelcomeActivity  apkFile.delete:");
//                        apkFile.delete();


                        builder.setContentText("Download complete")
                                .setProgress(0, 0, false);
                        mNotificationManager.notify(NOTIFY_ID, builder.build());

                    }


                    @Override
                    public void onFailure(int errorNo, String strMsg) {
                        super.onFailure(errorNo, strMsg);
                        L.d(errorNo + "====" + strMsg);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();

                        mNotificationManager.cancel(NOTIFY_ID);
                    }
                });


    }

}

